package com.md.api.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
 * 地址转经纬度（使用高德地图获取地址信息的经纬度）
 */
@Slf4j
public class AddressLocationUtil {
    /**
     * Key
     */
    private static String KEY="959af798d1446e6e8f552bb01c96a692";

    public  static String GD_URL="https://restapi.amap.com/v3/geocode/geo?address=%s&key=%s";
    public  static String TIP_URL="https://restapi.amap.com/v3/assistant/inputtips?keywords=%s&adcode=%s&key=%s";

    private static String BASE_DISTANCE = "http://restapi.amap.com/v3/distance?type=0&key=%s&origins=%s&destination=%s";

    /**
     * 成功标识
     */
    private static String SUCCESS_FLAG="1";

    /**
     * 根据地址获取对应的经纬度信息
     * @param address
     * @return
     */
    public static String getLonAndLatByAddress(String address){
        GD_URL = String.format(GD_URL, address, KEY);

        String jsonString = sendGet(GD_URL);
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        log.info("地址：{},获取对应的经纬度信息返回：{}",address,jsonObject.toJSONString());
        String location = jsonObject.getJSONArray("geocodes").getJSONObject(0).getString("location");
        return location;
    }


    public static JSONArray getAddressTip(String address,String adcode){
        TIP_URL = String.format(TIP_URL, address,adcode ,KEY);

        String jsonString = sendGet(TIP_URL);
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        log.info("地址：{},获取地址提示信息返回：{}",address,jsonObject.toJSONString());
        JSONArray array = jsonObject.getJSONArray("tips");
        return array;
    }
    /**
     * 发送请求
     *
     * @param serverUrl 请求地址
     */
    private static String getResponse(String serverUrl) {
        // 用JAVA发起http请求，并返回json格式的结果
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(serverUrl);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }


//    public static Integer getDistance(String startLonLat, String endLonLat) {
//        //返回起始地startAddr与目的地endAddr之间的距离，单位：米
//        Integer result = 0;
//        BASE_DISTANCE = String.format(BASE_DISTANCE, KEY, startLonLat,endLonLat);
//        //高德接口返回的是JSON格式的字符串
//        String queryResult = getResponse(BASE_DISTANCE);
//        JSONObject obj = JSONObject.parseObject(queryResult);
//        if(String.valueOf(obj.get("status")).equals(SUCCESS_FLAG)){
//            JSONArray geocodes = JSONArray.parseArray(JSONArray.toJSONString(obj.get("results")));
//            JSONObject geocode = JSONObject.parseObject(JSONObject.toJSONString(geocodes.get(0)));
//            result = Integer.valueOf(geocode.get("distance").toString());
//        }else{
//            throw new RuntimeException("地址转换经纬度失败，错误码：" + obj.get("infocode"));
//        }
//        return result;
//    }

    public static String getDistanceUrl(String origins, String destination) {
        String urlString = "http://restapi.amap.com/v3/distance?type=0&origins=" + origins + "&destination=" + destination + "&key=" + KEY;
        return urlString;
    }
    /**
     * 获取二个地点之间的直线距离
     * @param origins 出发地
     * @param destination 目的地
     * @return
     */
    public static Integer getDistance(String origins, String destination) {
        String jsonString = sendGet(getDistanceUrl(origins,destination));
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        Integer distance = jsonObject.getJSONArray("results").getJSONObject(0).getInteger("distance");
        return distance;
    }
    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            return null;
        } finally { // 使用finally块来关闭输入流
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    public static void main(String[] args) {
        System.out.println(getAddressTip("重庆南岸区通江大道","500000"));
//        System.out.println("经纬度：" + location);
//        System.out.println("当前城市：" + IpUtil.getAddressByIP());
//        System.out.println("距离：" + getDistance("106.470186,29.539380","106.470186,29.539380"));
//        System.out.println("距离：" + getDistance("106.470186,29.539380","106.374393,29.600494"));
//        System.out.println("距离：" + getDistance("106.470186,29.539380","106.656748,29.507978"));

    }
}
